from django import http
from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render
from django.views import View

from apps.boke_content.models import Blog, Category, Comment
from apps.index.models import Carousel
from utils import constants
from utils.response_code import RETCODE


class DetailView(View):

    def get(self, request, blog_id):
        username = request.COOKIES.get('username')

        blog_content = Blog.objects.filter(carousel__isnull=True).order_by('-create_time')
        blogs = Blog.objects.filter(carousel__isnull=True).order_by('-read_count')[:5]
        recommends = Blog.objects.filter(carousel__isnull=True, is_recommend=True)

        carousel = Carousel.objects.all()
        count = Blog.objects.all().count()
        next = int(blog_id) + 1
        if next > count:
            next = 1
            blog_content = Blog.objects.get(id=next)
        else:
            blog_content = Blog.objects.get(id=blog_id)
        blog_last = Blog.objects.get(id=int(blog_id) - 1)


        blog_next = Blog.objects.get(id=next)
        comments = Comment.objects.filter(blog_id=blog_id)

        blog_content.read_count += 1
        blog_content.save()
        categories = Category.objects.all()
        context = {
            'username': username,
            'blogs': blogs,
            'carousels': carousel,
            'recommends': recommends,
            'blog': blog_content,
            'comments': comments,
            'categories': categories,
            'last_blog': blog_last,
            'next_blog': blog_next
        }

        return render(request, 'base_detail.html', context=context)


class CommentView(View):

    def post(self, request):
        content = request.POST.get('content')
        blog_id = request.POST.get('blog_id')
        comment_id = request.POST.get('comment_id')
        print(content, blog_id)

        if not content:
            return http.JsonResponse({'code_s': RETCODE.NECESSARYPARAMERR, 'errmsg': '缺少参数'})

        user = request.user

        if not user.is_authenticated:
            return http.JsonResponse({'code_s': RETCODE.SESSIONERR, 'errmsg': '未登录'})

        try:
            blog = Blog.objects.get(id=blog_id)
        except Blog.DoesNotExist:
            return http.JsonResponse({'code_s': RETCODE.DBERR, 'errmsg': '没有找到该博客'})

        if comment_id is None:

            try:
                Comment.objects.create(content=content, user=user, blog=blog)
            except Comment.DoesNotExist:
                return http.JsonResponse({'code_s': RETCODE.DBERR, 'errmsg': '发布评论错误'})

            return http.JsonResponse({'code_s': RETCODE.OK, 'errmsg': '发布成功'})

        else:

            try:
                comment = Comment.objects.get(id=comment_id)
            except Comment.DoesNotExist:
                return http.JsonResponse({'code_s': RETCODE.DBERR, 'errmsg': '没有该评论'})

            try:
                Comment.objects.create(content=content, user=user, blog=blog, comment_id=comment)
            except Comment.DoesNotExist:
                return http.JsonResponse({'code_s': RETCODE.DBERR, 'errmsg': '发布评论错误'})

            return http.JsonResponse({'code_s': RETCODE.OK, 'errmsg': '发布成功'})


from haystack.generic_views import SearchView


class NewsSearchView(SearchView):
    """
    新闻搜索视图
    """
    # 设置搜索模板文件
    template_name = 'search/search.html'

    # 重写get请求，如果请求参数q为空，返回模型News的热门新闻数据
    # 否则根据参数q搜索相关数据
    def get(self, request, *args, **kwargs):
        # 1. 获取查询参数
        query = request.GET.get('q')
        # 2. 如果没有查询参数
        if not query:
            # 则返回热门新闻
            # 获取热门新闻对象, 包含外键标签, 查询数据并做筛选和排序
            hot_news = Blog.objects.all().order_by('-read_count')
            # 分页, 从配置文件中拿到haystack参数
            paginator = Paginator(hot_news, constants.GOODS_LIST_LIMIT)
            try:
                # 拿到前端传递的page,
                page = paginator.get_page(int(request.GET.get('page')))
            except Exception as e:
                # 如果出错则返回第一页,保证容错性
                page = paginator.get_page(1)

            return render(request, self.template_name, context={
                'page': page,
                # 'paginator': paginator,
                'query': query
            })
        # 3. 如果有查询参数
        else:
            # 则执行搜索
            return super().get(request, *args, **kwargs)

    def get_context_data(self, *args, **kwargs):
        """
        在context中添加page变量
        """
        context = super().get_context_data(*args, **kwargs)
        if context['page_obj']:
            # 捕获page_obj,将其赋值到page
            context['page'] = context['page_obj']
        return context
